/**
 * Cookie测试工具
 * 用于验证微前端架构下的token cookie设置
 */

/**
 * 测试cookie设置
 */
export const testCookieSetting = (token: string) => {
  console.log('🧪 [Cookie Test] Testing cookie setting...');

  try {
    const expires = new Date();
    expires.setTime(expires.getTime() + 7 * 24 * 60 * 60 * 1000);

    // 设置测试cookie
    document.cookie = `test_token=${encodeURIComponent(token)}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;

    // 立即读取验证
    const cookies = document.cookie.split(';');
    let found = false;

    for (const cookie of cookies) {
      const trimmedCookie = cookie.trim();
      if (trimmedCookie.startsWith('test_token=')) {
        const value = trimmedCookie.split('=')[1];
        const decodedToken = decodeURIComponent(value);
        if (decodedToken === token) {
          found = true;
          console.log('✅ [Cookie Test] Cookie setting and reading successful');
          console.log('🔑 [Cookie Test] Token:', `${decodedToken.substring(0, 20)}...`);
          break;
        }
      }
    }

    if (!found) {
      console.error('❌ [Cookie Test] Cookie setting failed');
    }

    // 清理测试cookie
    document.cookie = 'test_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
  } catch (error) {
    console.error('❌ [Cookie Test] Error:', error);
  }
};

/**
 * 检查当前所有cookie
 */
export const checkAllCookies = () => {
  console.log('🍪 [Cookie Test] Current cookies:');
  console.log(document.cookie);

  const cookies = document.cookie.split(';');
  cookies.forEach((cookie) => {
    const trimmed = cookie.trim();
    if (trimmed) {
      const [name, value] = trimmed.split('=');
      if (name === 'token') {
        try {
          const decoded = decodeURIComponent(value);
          console.log(`🔑 Token cookie: ${decoded.substring(0, 20)}...`);
        } catch (e) {
          console.log(`🔑 Token cookie (raw): ${value.substring(0, 20)}...`);
        }
      } else {
        console.log(`🍪 ${name}: ${value ? `${value.substring(0, 20)}...` : 'empty'}`);
      }
    }
  });
};

/**
 * 手动设置token到cookie（用于测试）
 */
export const manualSetToken = (token: string) => {
  console.log('🔧 [Cookie Test] Manually setting token to cookie...');

  try {
    const expires = new Date();
    expires.setTime(expires.getTime() + 7 * 24 * 60 * 60 * 1000);

    document.cookie = `token=${encodeURIComponent(token)}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
    document.cookie = `login_success=true; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;

    console.log('✅ [Cookie Test] Token manually set to cookie');
    checkAllCookies();
  } catch (error) {
    console.error('❌ [Cookie Test] Failed to set token:', error);
  }
};

// 将测试函数挂载到window对象，方便在控制台使用
if (typeof window !== 'undefined') {
  (window as any).cookieTest = {
    test: testCookieSetting,
    check: checkAllCookies,
    setToken: manualSetToken,
  };

  console.log('🛠️ Cookie测试工具已挂载到 window.cookieTest');
  console.log('可用命令: test(token), check(), setToken(token)');
}
